using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CrazyDogToDo.Entity.Data;

namespace CrazyDogToDo.Service.Services
{
    public class ActivityService
    {
        private CrazyDogToDoContext _crazy = new CrazyDogToDoContext();
        /// <summary>
        /// 调取显示所有未过期的公共活动
        /// </summary>
        /// <returns></returns>
        public List<Activity> GetAllActivity()
        {
            var activity = _crazy.Activity.Where(a => a.EndTime > DateTime.Now);
            return activity.ToList();
        }
        /// <summary>
        /// 创建公共活动
        /// </summary>
        /// <param name="email"></param>
        /// <param name="theme"></param>
        /// <param name="content"></param>
        /// <param name="endTime"></param>
        /// <param name="partNumber"></param>
        public bool CreateActivity(string email, string theme, string content, string endTime, int partNumber)
        {
            var user = _crazy.User.SingleOrDefault(u => u.Email.Equals(email));

            if (user != null)
            {
                var activity = new Activity()
                {
                    Theme = theme,
                    Content = content,
                    Email = email,
                    CreateTime = DateTime.Now,
                    EndTime = DateTime.Parse(endTime),
                    PartNumber = partNumber
                };
                _crazy.Activity.Add(activity);
                _crazy.SaveChanges();

            }
            return false;

        }

        public Activity GetActivityById(int id)
        {
            var activity = _crazy.Activity.SingleOrDefault(u => u.Id.Equals(id));
            return activity;
        }
        /// <summary>
        /// 加入活动
        /// </summary>
        /// <param name="email"></param>
        /// <param name="id"></param>
        public void JoinActivity(string email, int id)
        {
            var activity = _crazy.Activity.SingleOrDefault(u => u.Id.Equals(id));
            var inventory = _crazy.Inventory.Where(n => n.Email.Equals(email)).SingleOrDefault(m => m.Title.Equals("我的活动"));
            var matter = new Matter()
            {
                Email = inventory.Email,
                InventoryId = inventory.Id,
                Content = activity.Content,
                Remark = activity.Theme,
                CreateTime = activity.CreateTime,
                OverdueTime = activity.EndTime,
                State = false
            };

            var myActivityList = _crazy.Inventory.SingleOrDefault(u => u.Email.Equals(email) && u.Title.Equals("我的活动"));
            myActivityList.Matter.Add(matter);
            var user = _crazy.User.SingleOrDefault(u => u.Email.Equals(email));
            user.Score++;
            _crazy.SaveChanges();
        }
    }
}
